package io.bdmc.common.http;

import javax.annotation.PostConstruct;

import com.iotplatform.client.NorthApiClient;
import com.iotplatform.client.NorthApiException;
import com.iotplatform.client.dto.AuthOutDTO;
import com.iotplatform.client.dto.InvokeDeviceServiceOutDTO;
//import com.iotplatform.client.dto.QueryBatchSubInDTO;
import com.iotplatform.client.dto.QueryBatchSubOutDTO;
import com.iotplatform.client.dto.SubscriptionDTO;
import com.iotplatform.client.invokeapi.Authentication;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import io.bdmc.common.utils.RedisUtils;

@Service
public class CTAPI{

    @Autowired
    public RedisUtils _redis;
    private static CTAPI factory;
    public static final Logger logger = LoggerFactory.getLogger((CTAPI.class));
    
    @PostConstruct
    public void init() {
        factory = this;
    }
    public static String getAccessToken(){
        // get access token
        AuthOutDTO authOutDTO;
        
        String tk = factory._redis.get("CTAccessToken");
        if (tk != null && tk.length() > 1) {
           return tk;
        }

        /**---------------------initialize northApiClient------------------------*/
        NorthApiClient northApiClient = AuthUtil.initApiClient();
        northApiClient.getVersion();
        
        /**----------------------get access token-------------------------------*/
        System.out.println("======get access token======");
        Authentication authentication = new Authentication(northApiClient);
        
        try {
            authOutDTO = authentication.getAuthToken();
            factory._redis.set("CTAccessToken", authOutDTO.getAccessToken(),Long.valueOf(authOutDTO.getExpiresIn()));
        } catch (NorthApiException e) {
            logger.error(e.toString());
            e.printStackTrace();
            return "";
		}        
        return authOutDTO.getAccessToken();
    }

    public static QueryBatchSubOutDTO getAllSubs(String accesstoken){
        try {
            return AuthUtil.getAllSubs(accesstoken);
        } catch (NorthApiException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static  SubscriptionDTO SubscribeDeviceBussiness(String apiName,String accesstoken){
       return AuthUtil.SubscribeDeviceBussiness(apiName,accesstoken);
    }

    public static  SubscriptionDTO querySingleSub(String subId,String accesstoken){
        try {
            return AuthUtil.querySingleSub(subId, accesstoken);
        } catch (NorthApiException e) {
            e.printStackTrace();
            return null;
        }
     }

     public static InvokeDeviceServiceOutDTO sendXY(String deviceId,String accessToken){
         return AuthUtil.sendXY( deviceId, accessToken);
     }
}